//
//  TVPayFloatingView.swift
//  StarTimesON
//
//  Created by Toj on 12/1/22.
//  Copyright © 2022 StarTimes. All rights reserved.
//

import UIKit

protocol TVPayFloatingViewDelegate: NSObjectProtocol {
    func payFloatingViewDidTapBuyNow(_ view: TVPayFloatingView)
}

class TVPayFloatingView: UIView {
    
    weak var delegate: TVPayFloatingViewDelegate?
    
    // 优惠券
    var couponCellModel: TVCouponCellModel?
    // 加购
    var purchaseCellModel: TVAdditionalCommodityCellModel?
    // 支付渠道
    var channelViewModel: STChannelCellModel?
    
    // 确定规格信息
    var commodityCellModel: TVCommodityCellModel? { didSet {
        guard let commodity = commodityCellModel, let channel = channelViewModel else {
                  return
        }
        isHidden = false
        
        // 符号
        let symbol = commodity.currencySymbol
        actualSymbolLabel.text = symbol
        
        // 总价钱
        var totalPrice = Double(commodity.selectedNumberValue) * commodity.price
        
        // 优惠券的价钱
        couponView.isHidden = true
        var offMoney: Double = 0
        if let coupon = couponCellModel {
            couponView.isHidden = false
            offMoney = coupon.offPrice(totalPrice)
            let value = coupon.symbol + offMoney.st_moneyFormat.st_cleanZero
            let title = String(format: "membership_SignOut_Button1".localized(), "\(value)")
            couponView.setTitle(title, for: .normal)
        }
        
        // 加购价钱
        var purchasePrice: Double = 0
        if let purchase = purchaseCellModel {
            purchasePrice = purchase.price
        }
        totalPrice += purchasePrice
        // 最终价 = 折扣价总价钱 - 优惠券的价钱
        let finalPrice = totalPrice - offMoney
        commodity.startPrice = totalPrice
        commodity.endPrice = finalPrice
        actualPriceLabel.text = finalPrice.st_moneyFormat.st_cleanZero
        priceLabel.isHidden = totalPrice <= finalPrice
        if !priceLabel.isHidden {
            let priceString = symbol + totalPrice.st_moneyFormat.st_cleanZero
            let invalidPriceAttributed = priceString.to_attributedString(font: priceLabel.font, color: priceLabel.textColor, lineStyle: .strikethrough)
            priceLabel.attributedText = invalidPriceAttributed
        }
        
        buyButton.isEnabled = true
        if channel.isEWallet {
            channel.actualPayAmount = finalPrice
            // true: 货币符号一致 && 余额够用 && 是钱包
            //print("-->toj: isEW channel.isCanPay:\(channel.isCanPay)")
            buyButton.isEnabled = channel.isCanPay
        }
        //print("-->toj: isEW buyButton.isEnabled:\(buyButton.isEnabled)")
        setupViews()
    } }
    
    func startAnimationPrice(_ start: Double, to: Double) {
        //print("-->toj: start:\(start), to:\(to)")
        ds_couponPopup(type: .couponPopupClick)
        actualPriceLabel.start(start, end: to)
        ds_couponPopup(type: .animation)
    }
    
    @objc private func didTapBuy() {
        delegate?.payFloatingViewDidTapBuyNow(self)
    }
    
    @objc private func didTapBackground() { }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        setupMakeAddSubviews()
        
        actualPriceLabel.completionBlock = { [weak self] in
            self?.completionHandle()
        }
        
        let intercept = UITapGestureRecognizer(target: self, action: #selector(didTapBackground))
        addGestureRecognizer(intercept)
    }
    
    private func completionHandle() {
        guard let commodity = commodityCellModel else { return }
        // 商品吊牌价 - 优惠券的优惠价
        actualPriceLabel.text = commodity.endPrice.st_moneyFormat.st_cleanZero
        
        guard buyButton.isEnabled else { return }
        
        flowLightView.isHidden = false
        flowLightView.startFlowLightAnimation()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        setupMakeLayoutSubviews()
    }
    
    private lazy var buyButton: UIButton = {
        let view = UIButton()
        view.st_cornerRadius = cornerViewHeight * 0.5
        view.addTarget(self, action: #selector(didTapBuy), for: .touchUpInside)
        return view
    }()
    
    private lazy var actualSymbolLabel: UILabel = {
        let view = UILabel()
        view.textColor = "#554422".to_color
        view.font = UIFont.bold(with: 10.f_scale)
        return view
    }()
    
    private(set) lazy var actualPriceLabel: STNumberLabel = {
        let view = STNumberLabel()
        view.format = "%.2f"
        view.duration = 1
        view.transformStyle = .linear
        view.textColor = "#554422".to_color
        view.font = UIFont.bold(with: 21.f_scale)
        return view
    }()
    
    private lazy var priceLabel: UILabel = {
        let view = UILabel()
        view.textColor = "#775E33".to_color
        view.font = UIFont.bold(with: 10.f_scale)
        return view
    }()
    
    private lazy var buyStateView: UIView = {
        let view = UIView()
        view.isUserInteractionEnabled = false
        view.st_cornerRadius = buyStateViewHeight * 0.5
        return view
    }()
    
    private lazy var buyStateLabel: UILabel = {
        let view = UILabel()
        view.text = "pay".localized()
        view.textAlignment = .center
        view.isUserInteractionEnabled = false
        view.textColor = "#775E33".to_color
        view.font = UIFont.boldSystemFont(ofSize: 16.f_scale)
        return view
    }()
    
    private lazy var couponView: UIButton = {
        let view = STButton()
        view.spacing = 4
        view.titleAlignment = .right
        view.isUserInteractionEnabled = false
        view.setImage("commodity_coupon".to_image, for: .normal)
        view.setTitleColor("#775E33".to_color, for: .normal)
        view.titleLabel?.font = UIFont.boldSystemFont(ofSize: 10.f_scale)
        return view
    }()
    
    private let cornerViewHeight: CGFloat = 48
    private let buyStateViewHeight: CGFloat = 35
    
    private let buyEnabledColrs  = ["#F3D48B".to_color.cgColor,
                                    "#CDAC49".to_color.cgColor]
    private let buyDisabledColrs = ["#E9E9E9".to_color.cgColor,
                                    "#CCCCCC".to_color.cgColor]
    private let stateEnabledColrs  = ["#F4D069".to_color.cgColor,
                                      "#EDC345".to_color.cgColor]
    private let stateDisabledColrs = ["#E6E6E6".to_color.cgColor,
                                      "#D6D6D6".to_color.cgColor]
    
    private let borderColor = "#FFE498".to_color
    private let borderDisabledColor = "#E9E9E9".to_color
    
    private lazy var flowLightView: UIFlowLightView = {
       let view = UIFlowLightView()
        view.repeatCount = 3
        view.flowLightDuration = 0.7
        view.flowLightTimeInterval = 0.3
        view.isHidden = true
        return view
    }()
    
    deinit {
        print("-->toj: BuyNowFloatingView: deinit")
    }
}

// MARK: - 初始化
extension TVPayFloatingView {
    
    private func setupMakeAddSubviews() {
        addSubview(buyButton)
        addSubview(buyStateView)
        addSubview(buyStateLabel)
        addSubview(couponView)
        addSubview(flowLightView)
        
        buyButton.addSubview(actualSymbolLabel)
        buyButton.addSubview(actualPriceLabel)
        buyButton.addSubview(priceLabel)
    }
    
    private func setupMakeLayoutSubviews() {
        
        buyButton.snp.makeConstraints { make in
            make.top.equalTo(10.ui_scale)
            make.left.equalTo(16.ui_scale)
            make.right.equalTo(snp.right).offset(-16.ui_scale)
            make.height.equalTo(cornerViewHeight)
        }
        
        buyStateLabel.snp.makeConstraints { make in
            make.right.equalTo(buyButton.snp.right).offset(-22.ui_scale)
            make.centerY.equalTo(buyButton)
            make.width.greaterThanOrEqualTo(64)
        }

        buyStateView.snp.makeConstraints { make in
            make.right.equalTo(buyStateLabel.snp.right).offset(10.ui_scale)
            make.centerY.equalTo(buyStateLabel)
            make.left.equalTo(buyStateLabel.snp.left).offset(-10.ui_scale)
            make.height.equalTo(buyStateViewHeight)
        }

        couponView.snp.makeConstraints { make in
            make.left.right.equalTo(self)
            make.height.equalTo(26)
            make.top.equalTo(buyButton.snp.bottom)
        }
        
        flowLightView.snp.makeConstraints { make in
            make.edges.equalTo(buyButton)
        }

        setupRelayoutSubViews()
    }
    
    private func setupRelayoutSubViews() {
        
        actualSymbolLabel.sizeToFit()
        let left = actualSymbolLabel.frame.width + 20.ui_scale
        let actualPriceHeight = actualPriceLabel.text?.st_stringHeight(font: actualPriceLabel.font, maxWidth: STScreenWidth) ?? 0
        var priceHeight: CGFloat = 0
        if !priceLabel.isHidden {
            priceHeight = priceLabel.text?.st_stringHeight(font: priceLabel.font, maxWidth: STScreenWidth) ?? 0
        }
        let top = (cornerViewHeight - actualPriceHeight - priceHeight) * 0.5
        actualPriceLabel.snp.remakeConstraints { make in
            make.left.equalTo(left)
            make.top.equalTo(top)
        }
        
        actualSymbolLabel.snp.remakeConstraints { make in
            make.right.equalTo(actualPriceLabel.snp.left)
            make.bottom.equalTo(actualPriceLabel).offset(-3)
        }
        
        if priceLabel.isHidden { return }
        priceLabel.snp.remakeConstraints { make in
            make.left.equalTo(actualSymbolLabel)
            make.top.equalTo(actualPriceLabel.snp.bottom)
        }
    }
    
    private func setupViews() {
        setupRelayoutSubViews()
        var buyColors = buyEnabledColrs
        var stateColors = stateEnabledColrs
        var borderColor = borderColor
        if !buyButton.isEnabled {
            borderColor = borderDisabledColor
            buyColors = buyDisabledColrs
            stateColors = stateDisabledColrs
        }
        layoutIfNeeded()
        buyButton.st_border(color: borderColor)
        buyButton.gd_add(colors: buyColors, direction: .leftToRight)
        buyStateView.gd_add(colors: stateColors, direction: .leftToRight)
    }
}

extension TVPayFloatingView {
    
    // 优惠券弹窗  动画
    func ds_couponPopup(type: DSVAction.OTTMembership) {
        let event = DSEvent(category: DSVCategory.membershipList.rawValue, action: type.rawValue)
        DataStatistics.sendEvent(event: event)
    }
}
